<?php
use yii\helpers\Html;
use backend\assets\PrintAsset;
PrintAsset::register($this);
use backend\modules\statistics\assets\EchartsAsset;
EchartsAsset::register($this);
PrintAsset::register($this);
use common\models\business\NewBusinessInspection;
use common\models\business\NewBusinessInspectionData;
//取出距离预出栏报警的天数
$now = time();
if(!Yii::$app->request->get('days')){
    $outpre = \common\models\sys\SysSetting::getValue('waitout');
}else{
    $outpre = Yii::$app->request->get('days');
}

$outpretime = $now+($outpre*24*3600);

$this->title = '仔猪统计';

//出栏预警的体重
$outweight = 130;


//初始化状态的数量
foreach (\common\models\business\BusinessPig::$statues as $key => $row){
    $statotal[$key] = 0;
}
//预出栏的数量
$staprenum = 0;
//总量
$statotalnum = 0;
?>


<section class="wrapper site-min-height">
    <!-- page start-->
    <section class="panel">
        <header class="panel-heading">
              <?= Html::a('返回','javascript:history.back(-1)'); ?>  <?= Html::encode($this->title) ?>
        </header>


        <div class="row" style="margin-top:30px;">
            <div class="col-md-10 col-md-offset-1">
                <div class="panel-body progress-panel">
                    <form action=""  method="get" style="margin-bottom: 21px;width: 33%;">
                        <input type="text" value="" class="form-control" name="days" placeholder="距离<?=$outpre?>天出栏的猪有多少头" />
                    </form>


                    <div class="task-progress">
                        <h1>仔猪状态分布</h1>
                    </div>
                    <div class="task-option">
                    </div>
                </div>
                <table class="table table-hover">
                    <tbody>
                    <tr>
                        <th>
                            批次
                        </th>
                        <?php foreach (\common\models\business\BusinessPig::$statues as $key => $row){ ?>
                        <th>
                            <?= $row ?>
                        </th>
                        <?php } ?>
                        <th>预出栏</th>
                        <th>
                            总量
                        </th>
                    </tr>
                    <?php foreach ($result as $key => $row) { ?>
                        <tr>
                            <td>
                                <?= $key ?>
                            </td>
                            <?php foreach (\common\models\business\BusinessPig::$statues as $k => $v){ ?>
                                <?php
                                    if($key != '批次' && $key != '总量') {
                                        $statotal[$k] += array_key_exists('num', $row[$k]) ? $row[$k]['num'] : 0;
                                    }
                                ?>
                            <td>
                                <span class="btn btn-default btn showdetail" data-batch="<?=$key?>" data-status="<?= $v ?>" style="border:none;color:#fff;font-size:15px;background-color: <?= \common\models\business\BusinessPig::status2color($v); ?>"><?= array_key_exists('num',$row[$k])?$row[$k]['num']:0 ?></span>
                            </td>
                            <?php } ?>
                            <td>
                                <span class="btn btn-default btn showdetail" data-batch="<?=$key?>" data-status="预出栏" style="border:none;color:#fff;font-size:15px;background-color: #ccd232">
                                    <?php
                                        $pouts = (new \yii\db\Query())->select(new \yii\db\Expression('count(*)'))
                                            ->from(['p'=>\common\models\business\BusinessPig::tableName()])
                                            ->where('planout != 0 and planout<=:preout and batch=:batch',[':preout'=>$outpretime,':batch'=>$key])
                                            ->andWhere([
                                                    'id'=>(new \yii\db\Query())->select('ins.pigid')
                                                        ->from(['ins'=>NewBusinessInspection::tableName()])
                                                        ->leftJoin(['insd'=>NewBusinessInspectionData::tableName()],'inspectionid=ins.id')
                                                        ->where('insd.fieldname=\'体重\' and convert(insd.val,decimal(10,2))>=:outweight',[':outweight'=>$outweight])
                                                        ->orderBy('ins.createtime desc')
                                                        ->scalar()
                                                ])
                                            ->count();
                                        $staprenum += $pouts;
                                        echo $pouts;
                                ?>
                                </span>
                            </td>
                            <td>
                                <?= $row['total']?>
                            </td>
                            <?php $statotalnum += $row['total'] ?>
                        </tr>
                    <?php } ?>
                    <!--状态合计-->
                    <tr>
                        <td>
                            各状态合计
                        </td>
                        <?php foreach (\common\models\business\BusinessPig::$statues as $key => $row){ ?>
                        <td>
                            <?= $statotal[$key] ?>
                        </td>
                        <?php } ?>
                        <td>
                            <?= $staprenum ?>
                        </td>
                        <td>
                            <?= $statotalnum ?>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-md-10 col-md-offset-1" style="margin-top: 100px;">
                <div id="pignum" style="height: 500px;width: 90%;"></div>
            </div>
        </div>
    </section>
</section>



<!-- Modal -->
<div class="modal fade" id="numdetail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">详情</h4>
            </div>
            <div class="modal-body" style="height: 700px;overflow-y: scroll;">
                正在加载......
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>






<script>
    <?php $this->beginBlock('pignum') ?>
    //查看状态数量
    $('.showdetail').click(function(){
        var title = $(this).data('status')+'数量详情';
        $.get('/statistics/pig/get-statusnum',{batch:$(this).data('batch'),status:$(this).data('status'),outtime:<?=$outpretime?>},function(html){
            $('#numdetail').modal();
            $('#numdetail .modal-body').html(html);
            $('#numdetail .modal-title').html(title);
            $("#print").printPreview({
                obj2print:'#printarae',
                width:'810'
            });
        })
    })




    var option = {
        title : {
            text: '仔猪总体状态统计',
            subtext: '',
            x:'center'
        },
        color: ['#3398DB'],
        tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis : [
            {
                type : 'category',
                data : <?= json_encode($statusdata['type']) ?>,
                axisTick: {
                    alignWithLabel: true
                }
            }
        ],
        yAxis : [
            {
                type : 'value'
            }
        ],
        series : [
            {
                name:'数量',
                type:'bar',
                barWidth: '60%',
                data:<?= json_encode($statusdata['num']) ?>,
            }
        ]
    };

    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('pignum'));
    myChart.setOption(option);
    <?php $this->endBlock('pignum') ?>
    <?php $this->registerJs($this->blocks['pignum'],\yii\web\View::POS_END) ?>
</script>

